from django.shortcuts import render
import random,logging

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
# Create your views here.

from django_redis import get_redis_connection
from meiduo_mall.libs.yuntongxun.sms import CCP
from . import constains
from celery_tasks.sms.tasks import send_sms_code

logger = logging.getLogger('django')
#接口sms_codes/(?P<mobile>1[3-9]\d{9})/
class SMSCodeView(APIView):
    #短息验证码
    def get(self,request,mobile):
        # 创建连接到redis对象
        redis_conn = get_redis_connection('verify_codes')

        # 点击时读取redis的记录
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return Response({"message":'频繁发送短息验正码'},status=status.HTTP_400_BAD_REQUEST)

        #生成短信验证码
        sms_code = '%06d' % random.randint(0,999999)
        logger.info(sms_code)

        #创建redis管道对象，实现访问一次redis执行多条指定
        pl = redis_conn.pipeline()

        # 保存短信验证码到redis
        # redis_conn.setex('key','expire_time','value')
        # redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('sms_%s' % mobile, constains.SMS_CODE_REDIS_EXPIRES,sms_code)

        #向redis中添加一个标记数据　有效期６０秒
        # redis_conn.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.setex('send_flag_%s'%mobile,constains.SMS_CODE_REDIS_INTERVAL,1)

        pl.execute()

        #集成容联云通讯发送短信验证码
        # CCP().send_template_sms(mobile,[sms_code,constains.SMS_CODE_REDIS_EXPIRES // 60],1)

        #触发异步任务
        # delay用于触发异步任务
        send_sms_code.delay(mobile,sms_code)

        #响应结果
        return Response({'messsge':'OK'})